﻿// 后台清理服务
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Hosting;
using System.Threading.Tasks;
using System.Threading;
using System;

public class ConnectionCleanupService : BackgroundService
{
    private readonly IHubContext<ChatHub> _hubContext;

    public ConnectionCleanupService(
        IHubContext<ChatHub> hubContext)
    {
        _hubContext = hubContext;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            // 每 5 分钟清理一次
            await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);

            foreach (var userId in UserConnectionService.GetAllUsers())
            {
                var connections = UserConnectionService.GetConnectionIds(userId);
                foreach (var connId in connections)
                {
                    // 检查连接是否活跃
                    var client = _hubContext.Clients.Client(connId);
                    try
                    {
                        await client.SendAsync("CheckAlive");
                    }
                    catch
                    {
                        UserConnectionService.RemoveConnection(userId, connId);
                    }
                }
            }
        }
    }
}

